package com.cc.police.controller;


import com.alibaba.fastjson.JSON;
import com.cc.police.config.LoginRequired;
import com.cc.police.entity.PUser;
import com.cc.police.service.PUserService;
import com.cc.police.service.ex.PasswordNotMatchException;
import com.cc.police.service.ex.UserNotFoundException;
import com.cc.police.util.JsonResult;
import com.cc.police.util.JwtUtil;
import com.cc.police.util.RedisUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@CrossOrigin
public class PUserController extends BaseController{
    @Autowired
    PUserService pUserService;
    @Autowired
    RedisUtil redisUtil;


    @RequestMapping("login")
    @ResponseBody
    public JsonResult login(String username,String password, HttpServletRequest request)throws UserNotFoundException, PasswordNotMatchException {
        PUser pUser = new PUser();

        String token = "";
        JsonResult result = new JsonResult();
        try {

            System.err.println("用户名= "+username);
            System.err.println("密码= "+password);
            pUser.setUsername(username);
            pUser.setPassword(password);


            // 调用用户服务验证用户名和密码
            PUser umsMemberLogin = pUserService.login(pUser);

            if (umsMemberLogin != null) {
                // 登录成功

                // 用jwt制作token
                Integer userId = umsMemberLogin.getUserId();
                System.out.println("id== "+userId);
                String nickname = umsMemberLogin.getUsername();
                Map<String, Object> userMap = new HashMap<>();

                userMap.put("userId", userId);
                userMap.put("nickname", nickname);

                System.out.println("nickname==  "+nickname);
                System.out.println(umsMemberLogin.getPassword());
                System.out.println(umsMemberLogin.getSalt());

                String ip ="127.0.0.1";

//             按照设计的算法对参数进行加密后，生成token
                token = JwtUtil.encode("2020police", userMap, ip);

                // 将token存入redis一份
                pUserService.addUserToken(token, userId);

            } else {
                // 登录失败
                token = "fail";
            }
            System.err.println("登录生成"+token);
            result.setState(SUCCESS);
            result.setData(token);
        }catch (UserNotFoundException e){
            result.setMessage("用户名不存在");
        }catch (PasswordNotMatchException e){
            result.setMessage("密码错误");
        }

        return result;

    }


    /*退出登录*/
    @RequestMapping("logout")
    @ResponseBody
    @LoginRequired(loginSuccess = true)
    public JsonResult<Void> logout(HttpServletRequest request) {
        JsonResult result = new JsonResult();
        try {
            String token = request.getHeader("token");
            System.out.println("退出登录token=  "+token);
            Map<String, Object> decode = JwtUtil.decode(token, "2020police", "127.0.0.1");
            Object userId = decode.get("userId");
            Jedis jedis = redisUtil.getJedis();
            jedis.del("user:" + userId + ":token");

            result.setState(SUCCESS);
            result.setData("退出登录成功");
        }catch (Exception e){
            result.setMessage("出现异常");
        }
        return result;
    }


    /*用户密码修改*/
    @RequestMapping("/updatePassword")
    @ResponseBody
    @LoginRequired(loginSuccess = true)
    public JsonResult<Void> updatePassword(
            @RequestParam("password") String password
            , @RequestParam("newpassword") String newpassword,HttpServletRequest request){
        JsonResult result = new JsonResult();
        try {
            System.out.println("pass"+password);
            System.out.println("newpass"+newpassword);
            String token = request.getHeader("token");
            System.out.println("用户修改密码token=  "+token);
            Map<String, Object> decode = JwtUtil.decode(token, "2020police", "127.0.0.1");
            Object userId = decode.get("userId");

            pUserService.updetePassword(userId,password,newpassword);
            return new JsonResult<>(SUCCESS);
        }catch (PasswordNotMatchException e){
            result.setMessage("修改失败，原密码错误");
        }catch (Exception e){
            result.setMessage("修改失败，请重新尝试");
        }

        return result;
    }



    @RequestMapping("verify")
    @ResponseBody
    public String verify(String token, String currentIp, HttpServletRequest request) {
        System.out.println("开始校验token数据.........");
        // 通过jwt校验token真假
        Map<String, Object> map = new HashMap<>();

        Map<String, Object> decode = JwtUtil.decode(token, "2020police", currentIp);


            try {
                if (decode != null) {
                    Object userId = decode.get("userId");
                    Object nickname = decode.get("nickname");
                    System.out.println("检验userId="+userId);
                    System.out.println("检验nickname="+nickname);

                    Jedis jedis = redisUtil.getJedis();
                String token1 = jedis.get("user:" + userId + ":token");


                System.out.println("控制器校验token1="+token1);
                if(token1.equals(token)){
                    map.put("status", "success");
                    map.put("userId",userId);
                    map.put("nickname", nickname);
                    System.out.println("校验成功.........");
                }else {
                    map.put("status", "fail");
                    System.out.println("token校验失败.........");
                }


            } else {
                map.put("status", "fail");
                System.out.println("校验失败.........");
            }

            }catch (NullPointerException e){
                map.put("status", "fail");
                System.out.println("校验失败.........");
            }

        return JSON.toJSONString(map);
    }



    @RequestMapping("index")
    @ResponseBody
    @LoginRequired(loginSuccess = true)
    public String index() {

//        map.put("ReturnUrl", ReturnUrl);
        return "index 主页";
    }

    @RequestMapping("tologion")
    @ResponseBody
    public String tologion() {

//        map.put("ReturnUrl", ReturnUrl);
        return "token过期或不存在，请重新登录";
    }



    public static final int AVATAR_MAX_SIZE = 1 * 1024 * 1024;
    //文件类型格式
    public static final List<String> AVATAR_CONTENT_TYPES = new ArrayList<>();

    static {
        AVATAR_CONTENT_TYPES.add("image/jpeg");
        AVATAR_CONTENT_TYPES.add("image/jpg");
        AVATAR_CONTENT_TYPES.add("image/png");
    }

    /*设置页面 修改用户资料*/
    @RequestMapping(value = ("/updatephoto"), method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired(loginSuccess = true)
    public JsonResult<String> photo(
            @RequestParam("file") MultipartFile file ,String username,
            HttpServletRequest request) {
        JsonResult<String> result = new JsonResult<>();
        String token = request.getHeader("token");
        System.out.println("修改用户资料传的token=  "+token);
        Map<String, Object> decode = JwtUtil.decode(token, "2020police", "127.0.0.1");
        Object userId = decode.get("userId");
        System.out.println("设置修改用户资料userId= "+userId);

        List<String> list = new ArrayList<>();
//        System.out.println("上传出租房屋图片长度"+file.length);
        System.out.println("设置修改用户资料username= "+username);
//        for (MultipartFile files:file ) {
            // 检查文件是否为空
            if (file.isEmpty()) {
                result.setMessage("上传失败！请选择有效的文件！");
            }

            // 检查文件大小
            if (file.getSize() > AVATAR_MAX_SIZE) {
                result.setMessage("上传失败！不允许使用超过" + (AVATAR_MAX_SIZE / 1024) + "KB的文件！");
            }

            // 检查文件类型
            if (!AVATAR_CONTENT_TYPES.contains(file.getContentType())) {
                result.setMessage("上传失败！仅允许使用以下类型的图片文件：" + AVATAR_CONTENT_TYPES);
            }
            String dirName = "C:/work/temp/temp0/temp1/upload";
//        String dirName = new String("src/main/resources/" + "upload");
            File dir = new File(dirName);
            if (!dir.exists()) {
                dir.mkdirs();
                System.err.println("创建文件夹");
            }
            System.err.println("dir=" + dir);

            // 获取文件原名
            String originalFilename = file.getOriginalFilename();
            // 获取扩展名
            String suffix = "";
            int beginIndex = originalFilename.lastIndexOf(".");
            if (beginIndex != -1) {
                suffix = originalFilename.substring(beginIndex);
            }
            // 确定上传的文件名
            String filename = UUID.randomUUID().toString() + suffix;

            // 执行保存
            File dest = new File(dir.getAbsolutePath() + dir.separator + filename);


            try {
                file.transferTo(dest);
            } catch (IllegalStateException e) {
                result.setMessage("上传失败！请检查原文件是否存在并可以被访问！！");
            } catch (IOException e) {
                result.setMessage("上传失败！读取数据时出现未知错误！");
            }
            System.err.println("将文件保存到：" + dest);

            // 更新数据表

            String avatar = "/upload/" + filename;    //本地

            System.err.println(avatar);

            list.add(avatar);
            pUserService.updatePhotoAndName(avatar,username, (Integer) userId);
//        }

        result.setState(SUCCESS);
        result.setData1(list);

        return result;
    }


    @RequestMapping("showUser")
    @ResponseBody
    @LoginRequired(loginSuccess = true)
    public JsonResult<PUser> showUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        Map<String, Object> decode = JwtUtil.decode(token, "2020police", "127.0.0.1");
        Object userId = decode.get("userId");
        PUser data = pUserService.selectAllById(userId);


        return new JsonResult(SUCCESS,data);
    }


    /*修改用户名*/
    @RequestMapping("updateUsername")
    @ResponseBody
    @LoginRequired(loginSuccess = true)
    public JsonResult<PUser> updateUsername(@Param("username")String username,HttpServletRequest request ) {
        JsonResult result = new JsonResult();
        try {
            String token = request.getHeader("token");
            Map<String, Object> decode = JwtUtil.decode(token, "2020police", "127.0.0.1");
            Integer userId = (Integer) decode.get("userId");

            pUserService.updateUsername(username,userId);
            result.setState(SUCCESS);
        }catch (Exception e){
            result.setMessage("出现异常。修改失败");
        }


        return result;
    }




//    @RequestMapping("/upload/**")
//    @ResponseBody
//    public String selectByGrups(HttpServletRequest request) {
//        String url = request.getRequestURL().toString();
//        System.out.println("url=   "+url);
//
//
//        String[] data = url.split("/upload");
////        for (int i=0;i<data.length;i++){
////            strAllParam = data[i];
////            System.out.println(strAllParam);
////        }
//        String dd =data[0]+"/C:/work/temp/temp0/temp1/upload/"+data[1];
//
////        String
//        return dd;
//    }







}
